/* stylelint-disable block-no-empty */
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElInput, ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import * as XLSX from 'xlsx'
import qs from 'qs'
import { GetData, PostModifyAddress, PostRefund, patchAddRemarks, patchMarkedDelivery } from '@/api/modules/retailOrder.ts'
import useUserStore from '@/store/modules/user'
import PageNumber from '@/store/modules/PageNumberCache'
import { GetOptionData } from '@/api/modules/weibanuser.ts'

const userStore = useUserStore()
const route = useRoute()
const PageNumberCache = PageNumber()
const imgDomain = 'https://img1.eprhan.cc'
// 加载
const fullscreenLoading = ref(true)

const orderTypeArr = [
  { value: '', label: '全部' },
  { value: -7, label: '已退款' },
  { value: -3, label: '待发货退款' },
  { value: -4, label: '发货后退款' },
  { value: -2, label: '退款失败' },
  { value: -1, label: '待退款' },
  { value: 1, label: '待支付' },
  { value: 3, label: '已支付待发货' },
  { value: 4, label: '已发货' },
  { value: 7, label: '已付款' },
]

// 查询的表单
const findFrom = reactive({
  // 订单编号
  OrderNo: route.query.orderNo ? route.query.orderNo : '',
  // 物流单号
  WaybillId: '',
  // 收货人ID
  UserId: '',
  // 收货人
  ReceiverName: '',
  // 手机号
  ReceiverTelNumber: '',
  // 下单时间
  orderTime: [],
  // 商品ID
  ProductId: '',
  // 商品名称
  ProductName: '',
  // 订单类型
  orderType: '',
  // 拼团ID
  TuanId: route.query.tuanId ? route.query.tuanId : '',
  // 用户标签
  TagList: [],
})

let PageSize = 20
const total = ref(0) // 总数据数
const orderList: any = ref({})

// 导航栏
const orderStatus = ref('')

const orderRedactDialog = ref(false)
const addRemarksDialog = ref(false)
const kuaiDiDialog = ref(false)

interface RedactFromType {
  orderNo: string
  userName: string
  userPhone: string
  province: string
  city: string
  area: string
  address: string
  pca?: any
}

const orderRedactFrom = reactive<RedactFromType>({
  orderNo: '',
  userName: '',
  userPhone: '',
  province: '',
  city: '',
  area: '',
  address: '',
  pca: [],
})

function OrderRedact(item: any) {
  orderRedactDialog.value = true
  // console.log(item)
  orderRedactFrom.orderNo = item.orderNo
  orderRedactFrom.userName = item.userName
  orderRedactFrom.userPhone = item.userPhone
}

function SetSite() {
  orderRedactFrom.province = orderRedactFrom.pca[0]
  orderRedactFrom.city = orderRedactFrom.pca[1]
  orderRedactFrom.area = orderRedactFrom.pca[2]
  delete orderRedactFrom.pca
  // console.log(orderRedactFrom)
  PostModifyAddress(orderRedactFrom).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('修改成功')
      orderRedactDialog.value = false
      GetDataList(PageNumberCache.GetRetailOrderPage(), PageSize)
    }
    else {
      ElMessage.error(`修改失败。${res.error}`)
    }
  })
}

const remarksFrom = ref({
  orderNo: '',
  description: '',
})

const kuaiDi = ref({
  orderNo: '',
  kuaiDiGongSi: '',
  KuaiDiDanHao: '',
})

// 导航栏切换时的回调
function handleSelect(key: string) {
  findFrom.orderType = ''
  orderStatus.value = key
  fullscreenLoading.value = true
  GetDataList(PageNumberCache.GetRetailOrderPage(), PageSize)
}

// 查询
function Inquire() {
  fullscreenLoading.value = true
  GetDataList(PageNumberCache.GetRetailOrderPage(), PageSize)
}

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const orderType = findFrom.orderType ? findFrom.orderType : orderStatus.value
  const params = {
    PageIndex,
    PageSize,
    ...(orderType !== '' && { orderStatus: orderType }),
    ...(findFrom.OrderNo && { OrderNo: findFrom.OrderNo }),
    ...(findFrom.WaybillId && { WaybillId: findFrom.WaybillId }),
    ...(findFrom.UserId && { UserId: findFrom.UserId }),
    ...(findFrom.ReceiverName && { ReceiverName: findFrom.ReceiverName }),
    ...(findFrom.ProductId && { ProductId: findFrom.ProductId }),
    ...(findFrom.ProductName && { ProductName: findFrom.ProductName }),
    ...(findFrom.ReceiverTelNumber && { ReceiverTelNumber: findFrom.ReceiverTelNumber }),
    ...(findFrom.TuanId && { TuanId: findFrom.TuanId }),
    ...(findFrom.orderTime?.length > 0 && {
      AddTimeStart: findFrom.orderTime[0],
      AddTimeEnd: findFrom.orderTime[1],
    }),
    ...(findFrom.TagList && { TagList: findFrom.TagList }),
  }
  const parameter = qs.stringify(params)
  GetData(parameter).then((res: any) => {
    // console.log(res)
    if (res.succeeded) {
      orderList.value = res.data.items
      total.value = res.data.total
      fullscreenLoading.value = false
    }
    else {
      ElMessage.error('获取数据失败')
      fullscreenLoading.value = false
    }
  })
}

// Excel导出
const ExportSwitch = ref(false)
async function ExportExcel() {
  ExportSwitch.value = true
  const orderType = findFrom.orderType !== '' ? findFrom.orderType : orderStatus.value
  const params = {
    PageIndex: 1,
    PageSize: 100000,
    ...(orderType !== '' && { orderStatus: orderType }),
    ...(findFrom.OrderNo && { OrderNo: findFrom.OrderNo }),
    ...(findFrom.WaybillId && { WaybillId: findFrom.WaybillId }),
    ...(findFrom.UserId && { UserId: findFrom.UserId }),
    ...(findFrom.ReceiverName && { ReceiverName: findFrom.ReceiverName }),
    ...(findFrom.ProductId && { ProductId: findFrom.ProductId }),
    ...(findFrom.ProductName && { ProductName: findFrom.ProductName }),
    ...(findFrom.ReceiverTelNumber && { ReceiverTelNumber: findFrom.ReceiverTelNumber }),
    ...(findFrom.TuanId && { TuanId: findFrom.TuanId }),
    ...(findFrom.orderTime?.length > 0 && {
      AddTimeStart: findFrom.orderTime[0],
      AddTimeEnd: findFrom.orderTime[1],
    }),
    ...(findFrom.TagList && { TagList: findFrom.TagList }),
  }
  const parameter = qs.stringify(params)
  const excelData = await GetData(parameter)

  // 定义中文表头映射
  const headerMapping: any = {
    level: '会员级别',
    levelName: '会员名称',
    id: 'ID',
    orderNo: '订单编号',
    flag: '下单方式',
    orderSmallType: '订单类型',
    orderStatus: '订单状态',
    orderWDTStatus: '同步状态',
    orderDesp: '订单备注',
    postFee: '邮费',
    payAmount: '支付金额',
    discountPrice: '优惠价',
    userName: '收件人姓名',
    userPhone: '收件人手机号',
    province: '省',
    city: '市',
    area: '县',
    address: '详细地址',
    productBuyCount: '商品购买数量',
    kuaiDiGongSi: '快递公司',
    kuaiDiDanHao: '快递单号',
    addTime: '下单时间',
    transactionId: '微信支付交易id',
    productList: '商品明细',
    subscriberInfo: '用户信息',
    faHuoTime: '发货时间',
    tagList: '标签列表',
    payTime: '付款时间',
    payScore: '支付积分',
    tagList1: '标签1',
    tagList2: '标签2',
    tagList3: '标签3',
    tagList4: '标签4',
    tagList5: '标签5',
    tagList6: '标签6',
    tagList7: '标签7',
    tagList8: '标签8',
    tagList9: '标签9',
    tagList10: '标签10',
    tagList11: '标签11',
    tagList12: '标签12',
    tagList13: '标签13',
    tagList14: '标签14',
    tagList15: '标签15',
    tagList16: '标签16',
    tagList17: '标签17',
    subscriberInfoScOpenId: '用户OpenId',
    subscriberInfoUserPhone: '用户手机号',
    subscriberInfoUserNickName: '用户昵称',
    subscriberInfoUserId: '用户ID',
    productId: '商品ID',
    productName: '商品名称',
    productPrice: '商品价格',
    productQuantity: '商品数量',
    couponId: '优惠券ID',
    couponName: '优惠券名称',
    couponPrice: '优惠券面值',
    couponAddTime: '优惠券获取时间',
    couponEndTime: '优惠券有效期',
    couponUsedTime: '优惠券使用时间',
  } as { [key: string]: string }

  // 处理接口数据
  const newData = excelData.data.items.flatMap((item: any) => {
    // 合并order对象
    if (item.order && typeof item.order === 'object') {
      Object.assign(item, item.order)
    }

    // 状态映射
    const statusMappings: any = {
      flag: { 1: '单品', 2: '购物车' },
      orderStatus: {
        '1': '待支付',
        '3': '已支付待发货',
        '4': '已发货',
        '-4': '已发货退款',
        '-3': '未发货退款',
      },
      orderWDTStatus: { 0: '待同步', 1: '同步成功', 2: '同步失败' },
      orderSmallType: {
        0: '普通订单',
        31: '积分兑换',
        60: '积分混合',
        61: '现金秒杀',
        70: '任选n件',
        80: '团购订单',
        90: '开团订单',
        91: '参团订单',
      },
    }

    // 应用状态映射
    Object.keys(statusMappings).forEach((key) => {
      item[key] = statusMappings[key][item[key]] || ''
    })

    // 处理订阅者信息
    if (item.subscriberInfo) {
      item.subscriberInfoUserId = item.subscriberInfo.userId
      item.subscriberInfoUserNickName = item.subscriberInfo.userNickName
      item.subscriberInfoUserPhone = item.subscriberInfo.userPhone
      item.subscriberInfoScOpenId = item.subscriberInfo.scOpenId
    }

    // 处理标签列表
    const fixedTagMapping: any = {
      '包裹卡': 'tagList1',
      '包裹卡 2.0': 'tagList2',
      '包裹卡 2.1': 'tagList3',
      '抽奖活动': 'tagList4',
      '70团': 'tagList5',
      '六星街': 'tagList6',
      '可克达拉': 'tagList7',
      '那拉提': 'tagList8',
      '伊犁大学': 'tagList9',
      '包裹卡3.0': 'tagList10',
      '包裹卡3.0天猫': 'tagList11',
      '6月那拉提': 'tagList12',
      '6月70团': 'tagList13',
      '6月六星街': 'tagList14',
      '6月可克达拉': 'tagList15',
      '景区广告机六星街': 'tagList16',
      '景区广告机可克达拉': 'tagList17',
    }

    const tagListFields = ['tagList1', 'tagList2', 'tagList3', 'tagList4', 'tagList5', 'tagList6', 'tagList7', 'tagList8', 'tagList9', 'tagList10', 'tagList11', 'tagList12', 'tagList13', 'tagList14', 'tagList15', 'tagList16', 'tagList17']
    tagListFields.forEach((field) => {
      item[field] = ''
    });

    (item.tagList || []).forEach((tag: any) => {
      const field = fixedTagMapping[tag]
      if (field) {
        item[field] = tag
      }
    })

    // 处理会员等级信息
    if (item.levelInfo) {
      item.level = item.levelInfo.vipLevel
      item.levelName = item.levelInfo.vipName
    }

    // 删除不需要的字段
    const fieldsToDelete = ['order', 'subscriberInfo', 'tagList', 'levelInfo', 'cart_TicketCustomerIds', 'orderComment']
    fieldsToDelete.forEach((field) => {
      delete item[field]
    })

    // 获取商品和优惠券信息
    const products = item.productList || []
    const coupons = item.usedCouponList || []

    // 确定行数（取商品和优惠券数量的最大值）
    const rowCount = Math.max(products.length, coupons.length, 1)

    // 生成行数据
    const rows = []
    for (let i = 0; i < rowCount; i++) {
      const newItem = { ...item }

      // 处理商品信息
      if (i < products.length) {
        const product = products[i]
        newItem.productId = product.productId
        newItem.productName = product.productName
        newItem.productPrice = product.salePrice
        newItem.productQuantity = product.productNums
      }
      else {
        // 清除非首行的商品信息
        if (i > 0) {
          newItem.productId = ''
          newItem.productName = ''
          newItem.productPrice = ''
          newItem.productQuantity = ''
        }
      }

      // 处理优惠券信息
      if (i < coupons.length) {
        const coupon = coupons[i]
        newItem.couponId = coupon.couponInfo?.id || ''
        newItem.couponName = coupon.couponInfo?.name || ''
        newItem.couponPrice = coupon.couponInfo?.price || ''
        newItem.couponAddTime = coupon.addTime || ''
        newItem.couponEndTime = coupon.endTime || ''
        newItem.couponUsedTime = coupon.usedTime || ''
      }
      else {
        // 清除非首行的优惠券信息
        if (i > 0) {
          newItem.couponId = ''
          newItem.couponName = ''
          newItem.couponPrice = ''
          newItem.couponAddTime = ''
          newItem.couponEndTime = ''
          newItem.couponUsedTime = ''
        }
      }

      // 对于非首行，清除非商品和优惠券的信息
      if (i > 0) {
        Object.keys(newItem).forEach((key) => {
          if (![
            'productId', 'productName', 'productPrice', 'productQuantity',
            'couponId', 'couponName', 'couponPrice', 'couponAddTime', 'couponEndTime', 'couponUsedTime',
          ].includes(key)) {
            newItem[key] = ''
          }
        })
      }

      rows.push(newItem)
    }

    return rows
  })

  const wb = XLSX.utils.book_new()
  // 将数据中的键映射为中文表头
  const mappedData = newData.map((item: { [key: string]: any }) => {
    const newItem: { [key: string]: any } = {}
    Object.keys(headerMapping).forEach((key) => {
      newItem[headerMapping[key]] = item[key]
    })
    return newItem
  })

  const ws = XLSX.utils.json_to_sheet(mappedData)

  // 设置列宽
  ws['!cols'] = [
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 35 },
    { wch: 12 },
    { wch: 13 },
    { wch: 12 },
    { wch: 20 },
    { wch: 12 },
    { wch: 12 },
    { wch: 12 },
    { wch: 20 },
    { wch: 15 },
    { wch: 15 },
    { wch: 20 },
    { wch: 20 },
    { wch: 25 },
    { wch: 40 },
    { wch: 10 },
    { wch: 10 },
    { wch: 15 },
    { wch: 20 },
    { wch: 30 },
    { wch: 10 },
    { wch: 10 },
    { wch: 25 },
    { wch: 10 },
    { wch: 20 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 30 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 15 },
    { wch: 10 },
    { wch: 10 },
    { wch: 40 },
    { wch: 10 },
    { wch: 10 },
    { wch: 15 }, // 优惠券ID
    { wch: 20 }, // 优惠券名称
    { wch: 15 }, // 优惠券面值
    { wch: 20 }, // 优惠券获取时间
    { wch: 20 }, // 优惠券有效期
    { wch: 20 }, // 优惠券使用时间
  ]

  // 合并单元格
  const mergeRanges: any = []
  let rowIndex = 1
  excelData.data.items.forEach((item: { [key: string]: any }) => {
    const productCount = item.productList?.length || 1
    const couponCount = item.usedCouponList?.length || 1
    const rowCount = Math.max(productCount, couponCount, 1)

    // 合并除商品和优惠券外的所有列
    const columnsToMerge = Object.keys(headerMapping).filter(key =>
      !['productId', 'productName', 'productPrice', 'productQuantity',
        'couponId', 'couponName', 'couponPrice', 'couponAddTime', 'couponEndTime', 'couponUsedTime'].includes(key),
    ).map(key => headerMapping[key])

    for (let col = 0; col < columnsToMerge.length; col++) {
      if (rowCount > 1) {
        mergeRanges.push({
          s: { r: rowIndex, c: col },
          e: { r: rowIndex + rowCount - 1, c: col },
        })
      }
    }
    rowIndex += rowCount
  })

  // 设置合并范围
  ws['!merges'] = mergeRanges

  // 将工作表添加到工作簿中
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 写文件
  XLSX.writeFile(wb, '订单数据.xlsx')
  ExportSwitch.value = false
}

// 标签筛选
const activeNames = ref([0])
const tagDialog = ref(false)
const tagOptionList = ref<any>([])
function Open() {
  if (findFrom.TagList.length > 0) {
    tagOptionList.value.forEach((item: any) => {
      item.name.forEach((nameItem: any) => {
        nameItem.value = false
      })
    })

    // 如果有值则设为true
    tagOptionList.value.forEach((item: any) => {
      item.name.forEach((nameItem: any) => {
        findFrom.TagList.forEach((tagItem: any) => {
          if (tagItem === nameItem.name) {
            nameItem.value = true
          }
        })
      })
    })
  }
  tagDialog.value = true
}

function OnChange(index: any, indexs: any) {
  tagOptionList.value[index].name[indexs].value = !tagOptionList.value[index].name[indexs].value
}
// 清空所有标签
function ClearTag() {
  tagOptionList.value.forEach((item: any) => {
    item.name.forEach((nameItem: any) => {
      nameItem.value = false
    })
  })
}
// 提交标签并筛选数据
function TagScreen() {
  tagDialog.value = false
  findFrom.TagList = tagOptionList.value.flatMap((group: any) => group.name) // 将所有组的name数组合并成一个数组
    .filter((item: any) => item.value === true) // 筛选出value为true的对象
    .map((item: any) => item.name) // 提取name属性
}

// 追加备注
function AddRemarks(item: any) {
  remarksFrom.value.orderNo = item.orderNo
  addRemarksDialog.value = true
}
// 追加备注取消
function RemarksCancel() {
  remarksFrom.value.description = ''
  addRemarksDialog.value = false
}
// 追加备注确定
function RemarksConfirm() {
  const date = dayjs().format('YYYY-MM-DD HH:mm:ss')
  remarksFrom.value.description = `${userStore.account}_${date}：${remarksFrom.value.description}`
  patchAddRemarks(remarksFrom.value).then((res: any) => {
    if (res.succeeded) {
      RemarksCancel()
      fullscreenLoading.value = true
      GetDataList(PageNumberCache.GetRetailOrderPage(), PageSize)
      ElMessage.success('追加备注成功')
    }
  })
}

// 标记发货
function KuaiDi(item: any) {
  kuaiDi.value.orderNo = item.orderNo
  kuaiDiDialog.value = true
}
function MarkedDelivery() {
  const data = {
    ...kuaiDi.value,
  }
  patchMarkedDelivery(data).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('标记发货成功')
      kuaiDiDialog.value = false
      fullscreenLoading.value = true
      GetDataList(PageNumberCache.GetRetailOrderPage(), PageSize)
    }
  })
}
function cancelShipments() {
  kuaiDiDialog.value = false
  kuaiDi.value = {
    orderNo: '',
    kuaiDiGongSi: '',
    KuaiDiDanHao: '',
  }
}

// 手动同步
// function ManualSynchronization(item: any) {
//   console.log(item)
// }

// 退款
const RefundDialog = ref(false)
const RefundOrderNo = ref('')
const RefundorderStatus = ref(0)
const logisticsOrderNumber = ref('')
function Refund(orderNo: string, orderStatus: number) {
  RefundOrderNo.value = orderNo
  RefundorderStatus.value = orderStatus
  RefundDialog.value = true
}

function RefundSetData() {
  const params = {
    orderNo: RefundOrderNo.value,
    logisticsOrderNumber: logisticsOrderNumber.value,
  }

  PostRefund(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage({ type: 'success', message: '已退款' })
      if (Number(RefundorderStatus.value) === 3) {
        ElMessage({ type: 'success', message: '请于旺店通平台确认订单状态' })
      }
      RefundDialog.value = false
      fullscreenLoading.value = true
      GetDataList(PageNumberCache.GetRetailOrderPage(), PageSize)
    }
    else {
      ElMessage.error(`退款失败,${res.errors}`)
    }
  })
}

const nowPageNum = computed(() => {
  return PageNumberCache.GetRetailOrderPage()
})

function handleSizeChange(val: number) {
  fullscreenLoading.value = true
  GetDataList(PageNumberCache.GetRetailOrderPage(), PageSize)
  PageSize = val
}
function handleCurrentChange(val: number) {
  fullscreenLoading.value = true
  GetDataList(val, PageSize)
  PageNumberCache.SetRetailOrderPage(val)
}

onMounted(async () => {
  try {
    await GetOptionData().then((res: any) => {
      if (res.succeeded) {
        tagOptionList.value = res.data
        tagOptionList.value.forEach((item: any) => {
          if (Array.isArray(item.name)) {
            // 将name数组转换为对象数组
            item.name = item.name.map((nameItem: any) => ({
              name: nameItem,
              value: false,
            }))
          }
        })
      }
      else {
        ElMessage.error(`查询失败。${res.errors}`)
      }
    })

    await GetDataList(PageNumberCache.GetRetailOrderPage())
  }
  catch (error) {
    ElMessage.error(`${error}`)
  }
})
</script>

<template>
  <div>
    <el-menu :default-active="orderStatus" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="">
        全部订单
      </el-menu-item>
      <el-menu-item index="1">
        未付款订单
      </el-menu-item>
      <el-menu-item index="3">
        待发货订单
      </el-menu-item>
      <el-menu-item index="4">
        已发货订单
      </el-menu-item>
      <el-menu-item index="-7">
        已退款订单
      </el-menu-item>
    </el-menu>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="from-header">
          <el-form label-width="100">
            <div class="from">
              <el-form-item label="订单编号">
                <ElInput v-model="(findFrom.OrderNo as string)" placeholder="请输入订单编号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="快递单号">
                <ElInput v-model="findFrom.WaybillId" placeholder="请输入快递单号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="团ID">
                <ElInput v-model="(findFrom.TuanId as string)" placeholder="请输入团ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="用户ID">
                <ElInput v-model="findFrom.UserId" placeholder="请输入用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="收货人名称">
                <ElInput v-model="findFrom.ReceiverName" placeholder="请输入收货人名称" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="手机号">
                <ElInput v-model="findFrom.ReceiverTelNumber" placeholder="请输入手机号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="下单时间">
                <el-date-picker
                  v-model="findFrom.orderTime" type="datetimerange" clearable value-format="YYYY-MM-DD HH:mm:ss"
                  range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期"
                  @keyup.enter="Inquire"
                />
              </el-form-item>
              <el-form-item label="商品ID">
                <ElInput v-model="findFrom.ProductId" placeholder="请输入商品ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="商品名称">
                <ElInput v-model="findFrom.ProductName" placeholder="请输入商品名称" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="订单状态">
                <el-select v-model="findFrom.orderType" placeholder="请选择订单状态" clearable :disabled="orderStatus !== ''">
                  <el-option v-for="item in orderTypeArr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="标签">
                <el-select
                  v-model="findFrom.TagList"
                  multiple
                  placeholder="请筛选标签"
                >
                  <el-option
                    v-for="(item, index) in findFrom.TagList"
                    :key="index"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" :loading="ExportSwitch" @click="ExportExcel">
          导出
        </el-button>
        <el-button @click="Open">
          标签筛选
        </el-button>
      </div>
      <div v-loading="fullscreenLoading" class="body" style="min-height: 100px;">
        <el-card v-for="item in orderList" :key="item.orderNum" class="order">
          <template #header>
            <div>
              <span style="margin-right: 10px;">订单编号：<span style="font-weight: 600;">{{ item.orderNo }}</span></span>
              <el-tag :type="item.orderWDTStatus === 0 ? 'info' : item.orderWDTStatus === 1 ? 'success' : 'danger'">
                {{ item.orderWDTStatus === 0 ? '待同步'
                  : item.orderWDTStatus === 1 ? '同步成功'
                    : item.orderWDTStatus === 2 ? '同步失败'
                      : '未知状态' }}
              </el-tag>
            </div>
          </template>
          <!-- 基本信息 -->
          <div class="user-name">
            <el-avatar shape="square" :size="70" :src="item.subscriberInfo.userAvatar" />
            <div>
              <p>
                用户昵称：{{ item.subscriberInfo?.userNickName ? item.subscriberInfo?.userNickName : '未授权' }} ({{ item.subscriberInfo?.userId }})
                <span style="margin-left: 15px;">
                  用户授权手机号：{{ item.subscriberInfo?.userPhone ? item.subscriberInfo?.userPhone : '未授权手机号' }}
                </span>
              </p>
              <p>
                会员级别：{{ item.levelInfo?.vipLevel !== 0 ? item.levelInfo?.vipLevel : '未开通会员' }}
                <span v-if="item.levelInfo?.vipLevel !== 0" style=" margin-right: 15px;margin-left: 15px;">
                  会员名称：{{ item.levelInfo?.vipName }}
                </span>
                客户标签：<span v-if="item.tagList?.length !== 0">
                  <el-tag v-for="tag in item.tagList" :key="tag" style="margin-right: 10px;">
                    {{ tag }}
                  </el-tag>
                </span>
                <span v-else>
                  无
                </span>
              </p>
            </div>
          </div>
          <!-- 操作 -->
          <div class="button">
            <el-button v-if="item.orderStatus === 3" type="primary" @click="OrderRedact(item)">
              更改地址
            </el-button>
            <el-button v-if="item.orderStatus === 3" type="success" @click="KuaiDi(item)">
              标记发货
            </el-button>
            <!-- <el-button v-if="item.orderWDTStatus === 2" type="primary" @click="ManualSynchronization(item)">
              手动同步
            </el-button> -->
            <el-button v-if="item.orderStatus !== 1" type="primary" @click="AddRemarks(item)">
              追加备注
            </el-button>
            <el-button v-if="item.orderStatus === 3 || item.orderStatus === 4" type="warning" @click="Refund(item.orderNo, item.orderStatus)">
              退款
            </el-button>
          </div>
          <el-descriptions border :column="4">
            <!-- <el-descriptions-item label="用户ID">
              {{ item.subscriberInfo.userId }}
            </el-descriptions-item>
            <el-descriptions-item label="用户头像">
              <el-avatar shape="square" :size="40" :src="item.subscriberInfo.userAvatar" />
            </el-descriptions-item>
            <el-descriptions-item label="用户昵称">
              {{ item.subscriberInfo.userNickName }}
            </el-descriptions-item>
            <el-descriptions-item label="用户授权手机号">
              {{ item.subscriberInfo.userPhone }}
            </el-descriptions-item> -->
            <el-descriptions-item label="收货人">
              {{ item.userName }}[ {{ item.userPhone }} ]
            </el-descriptions-item>
            <el-descriptions-item label="收货地区">
              {{ item.province }}-{{ item.city }}-{{ item.area }}
            </el-descriptions-item>
            <el-descriptions-item label="详细地址">
              {{ item.address }}
            </el-descriptions-item>
            <el-descriptions-item label="支付金额">
              {{ item.payAmount }}
            </el-descriptions-item>
            <el-descriptions-item label="订单类型">
              <el-tag v-if="item.tuanId !== null && item.tuanId > 0">
                拼团订单
              </el-tag>
              <el-tag v-else>
                {{ item.orderSmallType === 0 ? '普通订单'
                  : item.orderSmallType === 31 ? '积分兑换'
                    : item.orderSmallType === 60 ? '积分混合'
                      : item.orderSmallType === 61 ? '现金秒杀'
                        : item.orderSmallType === 70 ? '任选n件'
                          : item.orderSmallType === 80 ? '团购订单'
                            : item.orderSmallType === 90 ? '开团订单'
                              : item.orderSmallType === 91 ? '参团订单' : '未定义' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item v-if="item.tuanId !== null && item.tuanId > 0" label="拼团ID">
              {{ item.tuanId }}
            </el-descriptions-item>
            <el-descriptions-item v-if="item.tuanId !== null && item.tuanId > 0" label="拼团状态">
              <el-tag>
                {{ item.tuanStatus === 0 ? '拼团中'
                  : item.tuanStatus === 1 ? '拼团成功'
                    : item.tuanStatus === 2 ? '拼团失败' : '未定义' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="下单方式">
              <el-tag>
                {{ item.flag === 1 ? '单品'
                  : item.flag === 2 ? '购物车' : '未定义' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="实付金额">
              {{ item.payAmount }}
            </el-descriptions-item>
            <el-descriptions-item label="快递公司">
              {{ item.kuaiDiGongSi ? item.kuaiDiGongSi : '暂未发货' }}
            </el-descriptions-item>
            <el-descriptions-item label="快递单号">
              {{ item.kuaiDiDanHao ? item.kuaiDiDanHao : '暂未发货' }}
            </el-descriptions-item>
            <el-descriptions-item label="支付积分">
              {{ item.payScore ? item.payScore : '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="下单时间">
              {{ item.addTime }}
            </el-descriptions-item>
            <el-descriptions-item v-if="item.orderStatus !== 1" label="付款时间">
              {{ item.payTime }}
            </el-descriptions-item>
            <el-descriptions-item v-if="item.orderStatus !== 1 && item.orderStatus !== 3" label="发货时间">
              {{ item.faHuoTime }}
            </el-descriptions-item>
          </el-descriptions>
          <!-- 优惠券 -->
          <el-card v-if="item?.usedCouponList?.length > 0" class="mt-1.5" shadow="never">
            <template #header>
              <span>优惠券</span>
            </template>
            <el-collapse>
              <el-collapse-item v-for="items in item.usedCouponList" :key="items.couponInfo.id">
                <template #title>
                  券名称：{{ items.couponInfo?.name }}
                  <el-tag v-if="items.inCart" type="primary" class="ml-2">
                    购物车
                  </el-tag>
                </template>
                <div class="grid mb-2" style="grid-template-columns: 1fr 4fr;">
                  <el-avatar shape="square" :size="80" :src="imgDomain + items.couponInfo?.picUrl" />
                  <el-descriptions :column="4">
                    <el-descriptions-item label="面值">
                      {{ items.couponInfo?.price }}
                    </el-descriptions-item>
                    <el-descriptions-item label="类型">
                      {{ items.couponInfo?.type === 1 ? '赠品券' : '' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="商品编码" :span="2">
                      {{ items.couponInfo?.productCode }}
                    </el-descriptions-item>
                    <el-descriptions-item label="获取时间">
                      {{ items.addTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="失效时间">
                      {{ items.endTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="使用时间">
                      {{ items.usedTime }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
          <!-- 表格 -->
          <div style="display: grid; grid-template-columns: 6fr 1fr;">
            <el-table :data="item.productList" stripe border>
              <el-table-column align="center" prop="productId" label="商品ID" width="80" />
              <el-table-column align="center" prop="productPic" label="商品图片" width="160">
                <template #default="scope">
                  <el-avatar shape="square" :size="50" :src="imgDomain + scope.row.productPic" />
                </template>
              </el-table-column>
              <el-table-column header-align="center" prop="productName" label="商品名称" show-overflow-tooltip min-width="300" />
              <el-table-column align="center" prop="salePrice" label="价格" />
              <el-table-column align="center" prop="productNums" label="数量" />
            </el-table>
            <div class="order-type">
              <div class="header">
                订单状态
              </div>
              <div class="order-type-text">
                {{ item.orderStatus === 1 ? '待付款'
                  : item.orderStatus === 3 ? '已付款'
                    : item.orderStatus === 4 ? '已发货'
                      : item.orderStatus === -3 ? '未发货 | 已退款'
                        : item.orderStatus === -4 ? '已发货 | 已退款'
                          : item.orderStatus === -2 ? '退款失败' : '' }}
              </div>
            </div>
          </div>
          <template v-if="item.orderDesp" #footer>
            {{ item.orderDesp }}
          </template>
        </el-card>
      </div>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        :default-current-page="nowPageNum"
        size="default"
        :background="false"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
    <!-- 修改收货地址的对话框 -->
    <el-dialog v-model="orderRedactDialog" title="修改收货地址" width="500" top="300px">
      <el-form :model="orderRedactFrom" label-position="right" label-width="120">
        <el-form-item label="手机号" style="margin-bottom: 10px;">
          <ElInput v-model="orderRedactFrom.userPhone" style="width: 240px;" />
        </el-form-item>
        <el-form-item label="省市区" style="margin-bottom: 10px;">
          <PcasCascader v-model="orderRedactFrom.pca" format="name" style="width: 240px;" />
        </el-form-item>
        <el-form-item label="详细地址">
          <ElInput v-model="orderRedactFrom.address" style="width: 240px;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orderRedactDialog = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetSite">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 追加备注 -->
    <el-dialog v-model="addRemarksDialog" title="追加备注" width="500" top="300px">
      <el-form :model="remarksFrom" label-position="right" label-width="50">
        <el-form-item label="备注">
          <ElInput
            v-model="remarksFrom.description" :autosize="{ minRows: 6, maxRows: 15 }"
            style="max-width: 400px;" type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="RemarksCancel">
            取消
          </el-button>
          <el-button type="primary" @click="RemarksConfirm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 标记发货 -->
    <el-dialog v-model="kuaiDiDialog" title="标记发货" width="500" top="300px">
      <el-form :model="remarksFrom" label-position="right" label-width="120">
        <el-form-item label="快递公司">
          <ElInput
            v-model="kuaiDi.kuaiDiGongSi"
            style="margin-bottom: 10px;"
          />
        </el-form-item>
        <el-form-item label="快递单号">
          <ElInput
            v-model="kuaiDi.KuaiDiDanHao"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelShipments">
            取消
          </el-button>
          <el-button type="primary" @click="MarkedDelivery">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 标签筛选 -->
    <el-dialog v-model="tagDialog" title="标签筛选" width="500" :destroy-on-close="true">
      <el-collapse v-model="activeNames">
        <el-collapse-item v-for="(item, index) in tagOptionList" :key="index" :title="item.group" :name="index">
          <div class="tag-box">
            <el-check-tag v-for="(items, indexs) in item.name" :key="indexs" :checked="items.value" type="primary" @change="OnChange(index, indexs)">
              {{ items.name }}
            </el-check-tag>
          </div>
        </el-collapse-item>
      </el-collapse>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ClearTag">
            清空
          </el-button>
          <el-button type="primary" @click="TagScreen">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 追加备注 -->
    <el-dialog v-model="RefundDialog" title="退款" width="500" top="300px">
      <div v-if="RefundorderStatus === 3">
        <p>[{{ RefundOrderNo }}]你确定要退款该订单吗？</p>
        <p style="color: red;">
          请确认好订单发货状态，旺店通同步有一定延迟
        </p>
      </div>
      <el-form v-else :model="remarksFrom" label-position="right" label-width="120">
        <p>
          该订单已发货，是否确认退款？
        </p>
        <el-form-item label="快递单号">
          <ElInput
            v-model="logisticsOrderNumber"
            style="max-width: 260px;"
            placeholder="快递单号（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="RefundDialog = false">
            取消
          </el-button>
          <el-button type="primary" @click="RefundSetData">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.from-header {
  display: grid;
  grid-template-columns: 8fr 1fr;
  margin-top: 1vh;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    grid-gap: 20px;
  }

  @media screen and (width <= 500px) {
    .from {
      grid-template-columns: repeat(auto-fill, minmax(30vw, 1fr));
    }
  }
}

.el-form-item {
  margin-bottom: 0;
}

.body {
  padding: 0 10px;

  .order {
    box-sizing: border-box;
    margin: 10px 0;
    background-color: white;
    border: 1px solid rgb(190 190 190);

    header {
      padding: 15px 5px;
      font-size: 19px;
    }

    .button {
      margin: 20px 0;
      text-align: right;
    }
  }
}

.redact-region {
  div {
    max-width: 80px;
    margin-right: 10px;
  }
}

.order-type {
  color: #9093a6;
  border: 1px solid #ebeef5;

  .header {
    height: 40px;
    padding: 10px 0;
    font-size: 13px;
    font-weight: 600;
    text-align: center;
    border-bottom: 1px solid #ebeef5;
  }

  .order-type-text {
    display: flex;
    align-items: center;
    justify-content: center;
    height: calc(100% - 40px);
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;
  margin-bottom: 10px;
  background-color: #f5f7fa;

  div {
    margin-left: 15px;
    text-align: left;

    p {
      font-size: 15px;
    }

    span {
      font-size: 15px;
    }
  }
}

.tag-box {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;

  span {
    margin-right: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    font-weight: 400;
  }
}
</style>
